package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.uu.utils.uuUtils;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.CustomizeDetailAdapter;
import com.hemaapp.yjnh.listener.OnItemClickListener;
import com.hemaapp.yjnh.bean.ClientDetails;
import com.hemaapp.yjnh.bean.CustomAddition;
import com.hemaapp.yjnh.bean.CustomBlogDetail;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.Reply;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.utils.LoginUtil;
import com.hemaapp.yjnh.view.ImageCarouselBanner;
import com.hemaapp.yjnh.view.ShareDialog;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.util.XtomWindowSize;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 田家的定制商品详情
 */
public class CustomizeProductionDetailActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.image_carousel_banner)
    ImageCarouselBanner imageCarouselBanner;
    @Bind(R.id.tv_A)
    TextView tvA;
    @Bind(R.id.tv_organic)
    TextView tvOrganic;
    @Bind(R.id.layout_head)
    FrameLayout layoutHead;
    @Bind(R.id.tv_goods_name)
    TextView tvGoodsName;
    @Bind(R.id.tv_price_old)
    TextView tvPriceOld;
    @Bind(R.id.tv_price_new)
    TextView tvPriceNew;
    @Bind(R.id.tv_coupons_count)
    TextView tvCouponsCount;
    @Bind(R.id.tv_assort)
    TextView tvAssort;
    @Bind(R.id.tv_unit)
    TextView tvUnit;
    @Bind(R.id.tv_sell_count)
    TextView tvSellCount;
    @Bind(R.id.tv_range)
    TextView tvRange;
    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.iv_merchant_avatar)
    ImageView ivMerchantAvatar;
    @Bind(R.id.tv_merchant_name)
    TextView tvMerchantName;
    @Bind(R.id.ratingBar)
    RatingBar ratingBar;
    @Bind(R.id.tv_merchant_address)
    TextView tvMerchantAddress;
    @Bind(R.id.iv_phone)
    ImageView ivPhone;
    @Bind(R.id.layout_merchant)
    LinearLayout layoutMerchant;
    @Bind(R.id.tv_detail)
    TextView tvDetail;
    @Bind(R.id.line_detail)
    View lineDetail;
    @Bind(R.id.layout_detail)
    RelativeLayout layoutDetail;
    @Bind(R.id.tv_addition)
    TextView tvAddition;
    @Bind(R.id.line_addition)
    View lineAddition;
    @Bind(R.id.layout_addition)
    RelativeLayout layoutAddition;
    @Bind(R.id.tv_reply)
    TextView tvReply;
    @Bind(R.id.line_reply)
    View lineReply;
    @Bind(R.id.layout_reply)
    RelativeLayout layoutReply;
    private TextView titleText;
    private ImageButton titleLeft;
    private Button titleRightBtn;
    private ImageView titleShare;
    private ImageView titleLove;

    private XtomRefreshLoadmoreLayout refreshlayout;
    private XtomListView listView;
    private TextView tvCustomize;
    private View headerView;
    private View headerView2;
    private TextView tvPackage;
    private TextView tvSpec;

    private String blog_id = "0";//商品id
    private CustomBlogDetail blog;//在需改已经发布过的商品时会用到
    private ClientDetails client;
    private CustomizeDetailAdapter adapter;
    private ArrayList<ImgItemsBean> detailsImg = new ArrayList<>();//详情图片
    private ArrayList<CustomAddition> additions = new ArrayList<>();
    private ArrayList<Reply> replies = new ArrayList<>();
    private User user;
    private LoginUtil.LoginCallBack loginCallBack;
    int page = 0;
    private int type = 1;//1商品详情，2附加属性，3评论

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_customize_production_detail);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        init();
        if (!blog_id.equals("0")) {
            String token = user == null?"":user.getToken();
            getNetWorker().getCustomBlog(token, blog_id);
        }
    }

    private void init() {
        headerView = LayoutInflater.from(mContext).inflate(R.layout.header_customize_detail, null);
        ButterKnife.bind(this, headerView);
        ivPhone.setOnClickListener(this);
        layoutDetail.setOnClickListener(this);
        layoutAddition.setOnClickListener(this);
        layoutReply.setOnClickListener(this);
        layoutMerchant.setOnClickListener(this);
        headerView2 = LayoutInflater.from(mContext).inflate(R.layout.header_customize_detail2, null);
        tvPackage = (TextView) headerView2.findViewById(R.id.tv_package);
        tvSpec = (TextView) headerView2.findViewById(R.id.tv_spec);
     }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void getExras() {
        blog_id = mIntent.getStringExtra("blog_id");
    }

    @Override
    protected void findView() {
        titleText = (TextView) findViewById(R.id.title_text);
        titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
        titleRightBtn = (Button) findViewById(R.id.title_right_btn);
        titleLove = (ImageView) findViewById(R.id.title_right_img);
        titleShare = (ImageView) findViewById(R.id.title_right_img2);

        refreshlayout = (XtomRefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
        listView = (XtomListView) findViewById(R.id.listview);
        listView.setFocusable(false);
        tvCustomize = (TextView) findViewById(R.id.tv_customize);
    }

    @Override
    protected void setListener() {
        titleText.setText("定制详情");
        titleRightBtn.setVisibility(View.GONE);
        titleLove.setVisibility(View.VISIBLE);
        titleShare.setVisibility(View.VISIBLE);
        titleShare.setImageResource(R.drawable.share);
        titleLeft.setOnClickListener(this);
        titleLove.setOnClickListener(this);
        titleShare.setOnClickListener(this);
        tvCustomize.setOnClickListener(this);
        refreshlayout.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {

            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                page = 0;
                String token = user == null?"":user.getToken();
                getNetWorker().blogGet(token, blog_id);
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                getNetWorker().replyList("3", blog_id, page+"");
            }
        });
    }

    private void setData() {
        if (blog.getSaleflag().equals("0")) {
            showTextDialog("商品已下架");
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    finish();
                }
            }, 1000);
            return;
        }
        String collectFlag = blog.getCollectflag();
        if (collectFlag == null || collectFlag.equals("0")) {
            titleLove.setImageResource(R.drawable.star_while_stroke);
        }else {
            titleLove.setImageResource(R.drawable.star_while);
        }
        tvGoodsName.setText(blog.getName());
        tvPriceNew.setText("¥"+uuUtils.formatAfterDot2(blog.getPrice()));
        tvPriceOld.setText("¥"+uuUtils.formatAfterDot2(blog.getOldprice()));
        tvPriceOld.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG ); //中间横线
        tvAssort.setText(blog.getTypename());
        tvUnit.setText("规格："+blog.getSpec());
        tvCouponsCount.setText(uuUtils.formatAfterDot2(blog.getScore())+"粮票");
        tvSellCount.setText("销量："+blog.getSellcount());
        ImageUtils.loadAvatar(mContext, client.getAvatar(), ivMerchantAvatar);
        tvMerchantName.setText(client.getNickname());
        String star = client.getStarscore();
        if (!isNull(star)) {
            ratingBar.setRating(Float.parseFloat(star));
        }
        tvMerchantAddress.setText(client.getAddress());
        tvRange.setText("产量范围："+blog.getYield_range()+blog.getGood_unit());
        tvDate.setText("交货时间："+blog.getSend_date());
        tvAddress.setText(blog.getSend_address());
        tvPackage.setText(blog.getContent());
//        tvSpec.setText("产品规格："+blog.getSpec());
        tvSpec.setVisibility(View.GONE);
        detailsImg.addAll((ArrayList<ImgItemsBean>) blog.getImg2Items());
        additions = (ArrayList<CustomAddition>) blog.getAddItems();
        initImagePager();
        //初始化第一页
        if (listView.getHeaderViewsCount() > 0) {
            listView.removeHeaderView(headerView);
            listView.removeHeaderView(headerView2);
        }
        listView.addHeaderView(headerView);
        listView.addHeaderView(headerView2);
        refreshData(-1);
    }

    private void initImagePager() {
        ArrayList<String> urls = new ArrayList<>();
        for (ImgItemsBean item : blog.getImgItems()) {
            urls.add(item.getImgurlbig());
        }
        imageCarouselBanner.getLayoutParams().height = XtomWindowSize.getWidth(mContext);
        layoutHead.getLayoutParams().height = XtomWindowSize.getWidth(mContext);
        imageCarouselBanner.onInstance(mContext, urls, R.drawable.ad_show_indicator,
                new ImageCarouselBlogClickListener(mContext, (ArrayList<ImgItemsBean>) blog.getImgItems()));
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
            case CLIENT_GET:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
            case CLIENT_GET:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
                HemaArrayResult<CustomBlogDetail> bResult = (HemaArrayResult<CustomBlogDetail>) baseResult;
                blog = bResult.getObjects().get(0);
                refreshlayout.refreshSuccess();
                if (blog == null) {
                    showTextDialog("获取商品信息失败！");
                    titleText.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            finish();
                        }
                    }, 2000);
                } else {
                    String token = user == null? "":user.getToken();
                    getNetWorker().clientGet(token, blog.getClient_id());//获取田家详细信息
                }
                break;
            case CLIENT_GET:
                HemaArrayResult<ClientDetails> uResult = (HemaArrayResult<ClientDetails>) baseResult;
                client = uResult.getObjects().get(0);
                setData();
                break;
            case REPLY_LIST:
                String page = netTask.getParams().get("page");
                HemaPageArrayResult<Reply> nResult = (HemaPageArrayResult<Reply>) baseResult;
                if (nResult == null || nResult.getObjects() == null)
                    return;
                ArrayList<Reply> replies = nResult.getObjects();
                if ("0".equals(page)) {// 刷新
                    refreshlayout.refreshSuccess();
                    refreshlayout.setLoadmoreable(true);
                    this.replies.clear();
                    this.replies.addAll(replies);
                } else {// 更多
                    refreshlayout.loadmoreSuccess();
                    if (replies.size() > 0)
                        this.replies.addAll(replies);
                    else {
                        refreshlayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                adapter.setReplies(this.replies);
                refreshData(-1);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                String oper = netTask.getParams().get("oper");
                // 操作	1添加 ，2取消 ;3：清空
                if (oper.equals("1")) {
                    XtomToastUtil.showShortToast(mContext, "添加收藏成功!");
                    titleLove.setImageResource(R.drawable.star_while);
                    ScaleAnimation scaleAnimation = new ScaleAnimation(0.0f, 1.4f, 0.0f, 1.4f,
                            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    scaleAnimation.setDuration(300);//设置动画持续时间
                    titleLove.startAnimation(scaleAnimation);
                    blog.setCollectflag("1");
                } else {
                    XtomToastUtil.showShortToast(mContext, "取消收藏成功!");
                    titleLove.setImageResource(R.drawable.star_while_stroke);
                    blog.setCollectflag("0");
                }
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，" + baseResult.getMsg());
                break;
            case CLIENT_GET:
                showTextDialog("获取商家信息失败，"+baseResult.getMsg());
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case REPLY_LIST:
                String page = netTask.getParams().get("page");
                if (page.equals("0")) {
                    refreshlayout.refreshFailed();
                }else {
                    refreshlayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "评论加载失败，"+baseResult.getMsg());
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                String oper = netTask.getParams().get("oper");
                // 操作	1添加 ，2取消 ;3：清空
                if (oper.equals("1")) {
                    showTextDialog("添加收藏失败!");
                }else {
                    showTextDialog("取消收藏失败!");
                }
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case CUSTOM_BLOG_GET:
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，请稍候再试");
                break;
            case CLIENT_GET:
                showTextDialog("获取信息失败!");
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case REPLY_LIST:
                String page = netTask.getParams().get("page");
                if (page.equals("0")) {
                    refreshlayout.refreshFailed();
                }else {
                    refreshlayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "评论加载失败");
                refreshData(failedType);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                String oper = netTask.getParams().get("oper");
                // 操作	1添加 ，2取消 ;3：清空
                if (oper.equals("1")) {
                    showTextDialog("添加收藏失败!");
                }else {
                    showTextDialog("取消收藏失败!");
                }
                break;
        }
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            if (loginCallBack != null)
                loginCallBack.onLogin();
        }
    }

    private void refreshData(int failed) {
        if (adapter == null) {
            adapter = new CustomizeDetailAdapter(mContext, detailsImg, additions, replies, type);
            adapter.setItemClickListener(new OnItemClickListener() {
                @Override
                public void onClickListener(final int position) {
                    if (type == 2) {//附加费用
                        CustomAddition addition = additions.get(position);
                        if (addition.isChecked())
                            addition.setChecked(false);
                        else
                            addition.setChecked(true);
                        adapter.notifyDataSetChanged();
                    }else if (type == 3) {//用户口碑回复
                        loginCallBack = new LoginUtil.LoginCallBack() {
                            @Override
                            public void onLogin() {
                                Intent itComment = new Intent(mContext, ReleaseBlogActivity.class);
                                itComment.putExtra("type", 3);
                                itComment.putExtra("blog_id", blog_id);
                                itComment.putExtra("reply", replies.get(position));
                                startActivity(itComment);
                                loginCallBack = null;
                            }
                        };
                        LoginUtil.getInstance(mContext, loginCallBack);
                    }
                }
            });
            if (user != null && user.getId().equals(blog.getClient_id())) {
                adapter.setOwner(true);
            }
            listView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        if (type == 1)
            adapter.setEmptyString("暂无图片介绍");
        else if (type == 2)
            adapter.setEmptyString("暂无附加费用");
        else if (type == 3)
            adapter.setEmptyString("暂无评价");
        adapter.setFailtype(failed);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_img:
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        String token = user.getToken();
                        if ("0".equals(blog.getCollectflag())) {//0未收藏；1收藏
                            getNetWorker().FolColOperate(token, "4", "1", blog.getId());
                        } else {//已关注
                            getNetWorker().FolColOperate(token, "4", "2", blog.getId());
                        }
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.title_right_img2:
                String sys_plugins = getApplicationContext().getSysInitInfo().getSys_plugins();
                String username = user == null? "":user.getUsername();
                String path = sys_plugins + "share/sdk.php?id=" + blog_id + "&customflag=1&username="+username;
                //图片url
                UMImage image = null;
                String imgUrl = blog.getImgurl();
                if (!isNull(imgUrl)) {
                    image = new UMImage(mContext, imgUrl);
                } else {
                    imgUrl = BaseUtil.getLogoImagePath(mContext);
                    image = new UMImage(mContext, BitmapFactory.decodeFile(imgUrl));
                }
                new ShareDialog(mContext, "分享商品", blog.getName(), path, image)
                        .builder().show();
                break;
            case R.id.tv_customize:
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        if (user.getId().equals(blog.getClient_id())) {
                            showTextDialog("不能定制自己的商品!");
                            return;
                        }
                        Intent it = new Intent(mContext, CustomizeConfirm1Activity.class);
                        it.putExtra("blog", blog);//已经选择的附加费用，保存在blog中传递给下个界面
                        it.putExtra("blog_id", blog.getId());
                        startActivity(it);
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.layout_merchant:
                Intent intent = new Intent();
                intent.putExtra("client_id", blog.getClient_id());
                intent.setClass(mContext, FarmerDetailsActivity.class);
                if (user != null) {
                    String id = user.getId();
                    if (id.equals(blog.getClient_id())) {
                        intent.setClass(mContext, MyFarmerActivity.class);
                    }
                }
                mContext.startActivity(intent);
                break;
            case R.id.layout_detail:
                reset();
                listView.setDividerHeight(0);
                tvDetail.setTextColor(getResources().getColor(R.color.theme_orange));
                lineDetail.setVisibility(View.VISIBLE);
                listView.addHeaderView(headerView2);
                type = 1;
                adapter.setType(1);
                refreshData(-1);
                break;
            case R.id.layout_addition:
                reset();
                listView.setDividerHeight(BaseUtil.dip2px(mContext, 10));
                tvAddition.setTextColor(getResources().getColor(R.color.theme_orange));
                lineAddition.setVisibility(View.VISIBLE);
                listView.removeHeaderView(headerView2);
                type = 2;
                adapter.setType(2);
                refreshData(-1);
                break;
            case R.id.layout_reply:
                reset();
                listView.setDividerHeight(0);
                tvReply.setTextColor(getResources().getColor(R.color.theme_orange));
                lineReply.setVisibility(View.VISIBLE);
                listView.removeHeaderView(headerView2);
                type = 3;
                adapter.setType(3);
                if (replies.size() == 0) {
                    page = 0;
                    getNetWorker().replyList("3", blog_id, page + "");
                }else
                    refreshData(-1);
                break;
            case R.id.iv_phone:
                final String phone = client.getMobile();
                if (phone != null && !phone.isEmpty() && !phone.equals("无")) {
                    HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
                    hbDialog.setText("是否直接拨打" + phone + "?");
                    hbDialog.setLeftButtonText("取消");
                    hbDialog.setRightButtonText("拨打");
                    hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                    hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                        @Override
                        public void onLeftButtonClick(HemaButtonDialog dialog) {
                            dialog.cancel();
                        }

                        @Override
                        public void onRightButtonClick(HemaButtonDialog dialog) {
                            dialog.cancel();
                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(
                                    "tel:" + phone));
                            startActivity(intent);
                        }
                    });
                } else {
                    XtomToastUtil.showShortToast(mContext, "对方没有提供电话号码");
                }
                break;
        }
    }

    private void reset() {
        tvDetail.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
        lineDetail.setVisibility(View.GONE);
        tvAddition.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
        lineAddition.setVisibility(View.GONE);
        tvReply.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
        lineReply.setVisibility(View.GONE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get( this ).onActivityResult( requestCode, resultCode, data);
    }
}
